﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
//using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using AvalonDock;
using System.Printing;
using System.Reflection;
using System.IO;
using Visifire.Charts;
using Visifire.Commons;
using AC.AvalonControlsLibrary.Controls;
using GDACNETAFFXLib;


namespace proyecto
{
    /// <summary>
    /// Lógica de interacción para Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
       
        //TabItem [] tabitems= new TabItem[20];
        /*DockPanel[] panels = new DockPanel[20];*/
        static int tabsN;

        public static int selectedTab;
        /*Vis[] visualizations = new Vis[20];
        int cont = 0;*/
        public static Tab[] tabs = new Tab[20];
        /*DockPanel[] subpanels = new DockPanel[20];
        public int Npanels;*/
        
        public static data [] dat;
        public static DockPanel[] filterPanels;

        int ndat;

        string SourceFile;

        public static string path;

        public static string user, pass;

        private Label countSelected;

        

        //public static readonly string curr = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).Clone().ToString();

        
        
        public Window1()
        {
            
            InitializeComponent();
            
            SourceFile = "";
            tabs[0] = new Tab();
            tabs[0].Background = Brushes.Transparent;
            tabs[0].HorizontalAlignment = HorizontalAlignment.Stretch;
            tabs[0].VerticalAlignment = VerticalAlignment.Stretch;
            //tabs[0].Children.Add(DockingManager x);
            page_1.Content = tabs[0];

            selectedTab = 0;
            //tabitems[0] = page_1;
            tabsN = 1;

            path = "";

            countSelected = new Label();


            calculation_tab.IsEnabled = false;
            transformation_tab.IsEnabled = false;
            visualization_tab.IsEnabled = false;

            /*Tab aux = new Tab();
            aux.HorizontalAlignment = HorizontalAlignment.Stretch;
            aux.VerticalAlignment = VerticalAlignment.Stretch;
            table_1.Content = aux;*/

            ndat = 0;
            dat = new data[20];
            filterPanels = new DockPanel[20];
            //Npanels=0;
            //tabs[0] = new Tab();
            try
            {
                //MessageBox.Show(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\transformations.ini");
                StreamReader reader = new StreamReader(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\transformations.ini");

                string[] transformations = reader.ReadToEnd().Trim().Split('\n');

                reader.Close();

                

                for (int i = 0; i < transformations.Length; i++)
                {
                    if (transformations[i] != "")
                    {

                        MenuItem t = new MenuItem();

                        t.Header = System.IO.Path.GetFileNameWithoutExtension(transformations[i]).Replace(System.IO.Path.GetDirectoryName(transformations[i]), "").Replace("\\", "");

                        t.Click += new RoutedEventHandler(ExistingTransformation);

                        CreateTable.Items.Add(t);
                    }

                }

                StreamReader Calcreader = new StreamReader(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\calculations.ini");

                string[] calculations = Calcreader.ReadToEnd().Trim().Split('\n');

                Calcreader.Close();

                for (int i = 0; i < calculations.Length; i++)
                {

                    //MessageBox.Show(i.ToString());
                    if (calculations[i] != "")
                    {

                        MenuItem t = new MenuItem();

                        t.Header = System.IO.Path.GetFileNameWithoutExtension(calculations[i]).Replace(System.IO.Path.GetDirectoryName(calculations[i]), "").Replace("\\", "");

                        t.Click += new RoutedEventHandler(ExistingCalculation);

                        Calculations.Items.Add(t);
                    }

                }
            }
            catch
            {

                MessageBox.Show("Unexpected fatal error while reading configuration files: Application must close");
                Close();
            }

            try
            {
                StreamReader reader = new StreamReader(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\netaffxLogin.txt");
                string[] read = reader.ReadToEnd().Trim().Split('\n', '\r');
                for (int i = 0; i < read.Length; i++)
                    read[i].Trim().Replace("\r", "").Replace("\n", "");

                if (read.Length > 1)
                {
                    user = read[0];
                    pass = read[1];
                    string auxPass = "";
                    for (int i = 0; i < pass.Length; i = i+4)
                        auxPass = auxPass + pass[i + 3];
                    pass = auxPass;

                }

                else
                {
                    user = "";
                    pass = "";
                }
            }

            catch
            {

                MessageBox.Show("Unexpected fatal error while reading configuration files: Application must close");
                Close();
            }
            
            
        }

        

        /*MemoryStream savedLayout = new MemoryStream();

        private void ShowDockingManager_Click(object sender, RoutedEventArgs e)
        {
            savedLayout.Position = 0;
            _dockingManager.RestoreLayout(savedLayout);
            _dockingManager.Hide(ShowMeFirst);
            savedLayout.Close();
        }


        private void _dockingManager_Loaded(object sender, RoutedEventArgs e)
        {
            _dockingManager.SaveLayout(savedLayout);

            _dockingManager.Hide(ShowMeSecond);
            _dockingManager.Hide(AlsoShowMeSecond);

        }
         
        
        <ContentControl x:Name="TestContainer">
                    <ad:DockingManager x:Name="_dockingManager" Loaded="_dockingManager_Loaded">
                    </ad:DockingManager>
                </ContentControl>
         */

        
        void Window_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        private void new_Click(object sender, RoutedEventArgs e)
        {

        }

        private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void new_document_Click(object sender, RoutedEventArgs e)
        {
            if (ndat > 0)
            {
                saveQuestion question = new saveQuestion();
                question.ShowDialog();
                if (question.result())
                {
                    bool filename = true;
                    if (SourceFile == "")
                    {
                        filename = false;
                        SaveFileDialog open = new SaveFileDialog();
                        open.DefaultExt = ".miv";
                        open.AddExtension = true;
                        filename = open.ShowDialog().Value;
                        if (filename)
                            SourceFile = open.FileName;
                    }

                    if (filename)
                    {
                        try
                        {
                            saveDocument();
                        }
                        catch
                        {
                            MessageBox.Show("Error while saving document");

                        }
                    }
                }

                destroyDocument();
            }

        }

        private void exit_Click(object sender, RoutedEventArgs e)
        {
            //downloadCDF("prueba");

            if (ndat > 0)
            {
                saveQuestion question = new saveQuestion();
                question.ShowDialog();
                if (question.result())
                {
                    bool filename = true;
                    if (SourceFile == "")
                    {
                        filename = false;
                        SaveFileDialog open = new SaveFileDialog();
                        open.DefaultExt = ".miv";
                        open.AddExtension = true;
                        filename = open.ShowDialog().Value;
                        if (filename)
                            SourceFile = open.FileName;
                    }

                    if (filename)
                    {
                        try
                        {
                            saveDocument();
                        }
                        catch
                        {
                            MessageBox.Show("Error while saving document");

                        }
                    }
                }

            }

            string current = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            if (System.IO.Directory.Exists(current + "/temp"))
            {
                try
                {
                    System.IO.Directory.Delete(current + "\\temp", true);
                }

                catch /*(System.IO.IOException i)*/
                {
                    //Console.WriteLine(i.Message);
                }
            }


            this.Close();
        }

        private void open_document_Click(object sender, RoutedEventArgs e)
        {

            while (resizingPanel1.Children.Count > 0)
                resizingPanel1.Children.Remove(resizingPanel1.Children[0]);

            if (ndat > 0)
            {
                saveQuestion question = new saveQuestion();
                question.ShowDialog();
                if (question.result())
                {
                    bool filename = true;
                    if (SourceFile == "")
                    {
                        filename = false;
                        SaveFileDialog open = new SaveFileDialog();
                        open.DefaultExt = ".miv";
                        open.AddExtension = true;
                        filename = open.ShowDialog().Value;
                        if (filename)
                            SourceFile = open.FileName;
                    }

                    if (filename)
                    {
                        try
                        {
                            saveDocument();
                        }
                        catch
                        {
                            MessageBox.Show("Error while saving document");

                        }
                    }
                }

                destroyDocument();
            }

            OpenFileDialog load = new OpenFileDialog();

            if (!load.ShowDialog().Value)
            {
                return;
            }

            StreamReader reader = new StreamReader(load.FileName);

            string[] fileRows = reader.ReadToEnd().Trim().Split('\n');

            string[][] fileCells = new string[fileRows.Length][];

            for (int i = 0; i < fileRows.Length; i++)
            {

                fileCells[i] = fileRows[i].Trim().Split('\t');
            }

            InitializeComponent();
            tabs[0] = new Tab();
            tabs[0].Background = Brushes.Transparent;
            tabs[0].HorizontalAlignment = HorizontalAlignment.Stretch;
            tabs[0].VerticalAlignment = VerticalAlignment.Stretch;
            
            while(Tabs1.Items.Count > 0)
            {
                Tabs1.Items.Remove(Tabs1.Items[Tabs1.Items.Count-1]);
            }

            page_1 = new TabItem();
            page_1.Content = tabs[0];
            //tabitems[0] = page_1;
            tabsN = 1;
            Tabs1.Items.Add(page_1);
            Tabs2 = new TabControl();

            ndat = 0;
            dat = new data[20];
            filterPanels = new DockPanel[20];

            ndat = Convert.ToInt16(fileCells[0][0]);

            int nCols = Convert.ToInt16(fileCells[2][1]);
            int nRows = Convert.ToInt16(fileCells[2][0]);
            int ntables = Convert.ToInt16(fileCells[1][0]);

            string [] types = new string[Convert.ToInt16(fileCells[2][1])];
            DataTable table = new DataTable(fileCells[4][0].ToString());
            for (int i = 0; i < types.Length; i++)
            {
                
              
                types[i] = fileCells[3][i].ToString();

                //MessageBox.Show(types[i]);

                switch (types[i])
                {
                    case "String":

                        DataColumn column = new DataColumn(fileCells[5][i].ToString(), typeof(string));
                        table.Columns.Add(column);
                        //MessageBox.Show("string");
                        break;
                    case "Int":
                        DataColumn column1 = new DataColumn(fileCells[5][i].ToString(), typeof(int));
                        table.Columns.Add(column1);
                        break;

                    case "Bool":
                        DataColumn column2 = new DataColumn(fileCells[5][i].ToString(), typeof(bool));
                        table.Columns.Add(column2);
                        break;
                    case "Double":
                        DataColumn column3 = new DataColumn(fileCells[5][i].ToString(), typeof(double));
                        table.Columns.Add(column3);
                        //MessageBox.Show("double");
                        break;
                }
            }

            for (int i = 0; i<nRows; i++){
                DataRow row = table.NewRow();

                for (int j = 0; j < nCols; j++){

                    switch (types[j])
                    {

                        case "String":
                            row[j] = (fileCells[6 + i][j]);
                            break;

                        case "Int":
                            row[j] = Convert.ToInt16(fileCells[6 + i][j]);
                            break;
                        case "Double":
                            row[j] = Convert.ToDouble(fileCells[6 + i][j]);
                            break;
                        case "Bool":
                            row[j] = Convert.ToBoolean(fileCells[6 + i][j]);
                            break;
                    }
                    
                }

                table.Rows.Add(row);

            }

            dat[0] = new data();

            dat[0].AddTable(table, nCols, nRows);

            dat[0].createFilters();

            int pointer = 6 + nRows;

            for (int tableIndex = 1; tableIndex < ntables; tableIndex++)
            {

                DataTable table_ = new DataTable(fileCells[pointer][0].ToString());
                table_.TableName = fileCells[pointer][0].ToString(); pointer = pointer + 2;

                if (table_.TableName == "Correlation Matrix")
                {
                    dat[0].createCorrelationMatrix();
                    pointer--;
                    //MessageBox.Show("entra");
                }

                else
                {

                    table_ = table.Clone();

                    for (int i = 0; i < nRows; i++)
                    {
                        DataRow row = table_.NewRow();

                        for (int j = 0; j < nCols; j++)
                        {

                            switch (types[j])
                            {

                                case "String":
                                    row[j] = (fileCells[pointer + i][j]);
                                    break;

                                case "Int":
                                    row[j] = Convert.ToInt16(fileCells[pointer + i][j]);
                                    break;
                                case "Double":
                                    row[j] = Convert.ToDouble(fileCells[pointer + i][j]);
                                    break;
                                case "Bool":
                                    row[j] = Convert.ToBoolean(fileCells[pointer + i][j]);
                                    break;
                            }

                        }

                        table_.Rows.Add(row);

                    }

                    dat[0].AddTable(table_, nCols, nRows);
                    pointer = pointer + nRows;
                }

                

            }

            tabsN = Convert.ToInt16(fileCells[pointer][0]);

            pointer++;

            for (int i = 0; i < tabsN; i++)
                tabs[i] = new Tab();

            

            tabs[0].Name = fileCells[pointer][0].Replace(" ", "_"); pointer++;

            page_1.Header = tabs[0].Name;

            int nVis = Convert.ToInt16(fileCells[pointer][0]); pointer++;

            int visT;

            for (int i = 0; i<nVis; i++){
                visT = Convert.ToInt16(fileCells[pointer][0]); pointer++;
                tabs[0].AddVisualization(dat[0], visT, 0);

                switch(visT){
                    case 0:
                        tabs[0].getVis(i).setNSeries(Convert.ToInt16(fileCells[pointer][0]));
                        tabs[0].getVis(i).setTable(Convert.ToInt16(fileCells[pointer][1])); pointer++;
                        for (int j = 0; j<tabs[0].getVis(i).getNSeries(); j++){

                            tabs[0].getVis(i).setSerie(j, Convert.ToInt16(fileCells[pointer][j]));

                        }pointer++;
                        tabs[0].getVis(i).setNSteps(Convert.ToInt16(fileCells[pointer][0]));

                        pointer++;

                        break;

                    case 2:

                        tabs[0].getVis(i).setTable(Convert.ToInt16(fileCells[pointer][0])); pointer++;
                        
                        //tabs[0].getVis(i).setNSeries(nRows);
                        for (int j = 0; j<nRows; j++){

                            tabs[0].getVis(i).setSerie(j, Convert.ToInt16(fileCells[pointer][j]));

                        }                        

                        pointer++;

                        break;

                    case 4:

                        tabs[0].getVis(i).setNSeries(Convert.ToInt16(fileCells[pointer][0]));
                        tabs[0].getVis(i).setTable(Convert.ToInt16(fileCells[pointer][1])); pointer++;
                        for (int j = 0; j<tabs[0].getVis(i).getNSeries(); j++){

                            tabs[0].getVis(i).setSerie(j, Convert.ToInt16(fileCells[pointer][j]));

                        }

                        pointer++;

                        break;

                    case 5:

                        tabs[0].getVis(i).setTable(Convert.ToInt16(fileCells[pointer][1]));
                        tabs[0].getVis(i).setNSeries(Convert.ToInt16(fileCells[pointer][0]));                         pointer++;
                        for (int j = 0; j<tabs[0].getVis(i).getNSeries(); j++){

                            tabs[0].getVis(i).setSerie(j, Convert.ToInt16(fileCells[pointer][j]));

                        }

                        pointer++;

                        break;

                }
            }

            tabs[0].refresh(dat[0], 0);
            page_1.Content = tabs[0];

            TabItem auxtab = new TabItem();
            Tabs1.Items.Add(auxtab);
            Tabs1.Items.Remove(auxtab);


            for (int tabCont = 1; tabCont < tabsN; tabCont++)
            {
                TabItem tabitem = new TabItem();
                tabitem.Header = fileCells[pointer][0]; pointer++;

                tabs[tabCont].Name = (tabitem.Header as string).Replace(" ", "_");
                Tabs1.Items.Add(tabitem);
                nVis = Convert.ToInt16(fileCells[pointer][0]); pointer++;

                for (int i = 0; i < nVis; i++)
                {
                    visT = Convert.ToInt16(fileCells[pointer][0]); pointer++;
                    tabs[tabCont].AddVisualization(dat[0], visT, 0);

                    switch (visT)
                    {
                        case 0:
                            tabs[tabCont].getVis(i).setNSeries(Convert.ToInt16(fileCells[pointer][0]));
                            tabs[tabCont].getVis(i).setTable(Convert.ToInt16(fileCells[pointer][1])); pointer++;
                            for (int j = 0; j < tabs[tabCont].getVis(i).getNSeries(); j++)
                            {

                                tabs[tabCont].getVis(i).setSerie(j, Convert.ToInt16(fileCells[pointer][j]));

                            } pointer++;
                            tabs[tabCont].getVis(i).setNSteps(Convert.ToInt16(fileCells[pointer][0]));

                            pointer++;

                            break;

                        case 2:

                            tabs[tabCont].getVis(i).setTable(Convert.ToInt16(fileCells[pointer][0])); pointer++;
                            //pointer++;
                            for (int j = 0; j < nRows; j++)
                            {

                                tabs[tabCont].getVis(i).setSerie(j, Convert.ToInt16(fileCells[pointer][j]));

                            }

                            pointer++;

                            break;

                        case 4:

                            tabs[tabCont].getVis(i).setNSeries(Convert.ToInt16(fileCells[pointer][0]));
                            tabs[tabCont].getVis(i).setTable(Convert.ToInt16(fileCells[pointer][1])); pointer++;
                            for (int j = 0; j < tabs[tabCont].getVis(i).getNSeries(); j++)
                            {

                                tabs[tabCont].getVis(i).setSerie(j, Convert.ToInt16(fileCells[pointer][j]));

                            }

                            pointer++;

                            break;

                        case 5:

                            tabs[tabCont].getVis(i).setTable(Convert.ToInt16(fileCells[pointer][0]));
                            tabs[tabCont].getVis(i).setNSeries(Convert.ToInt16(fileCells[pointer][1])); pointer++;
                            for (int j = 0; j < tabs[tabCont].getVis(i).getNSeries(); j++)
                            {

                                tabs[tabCont].getVis(i).setSerie(j, Convert.ToInt16(fileCells[pointer][j]));

                            }

                            pointer++;

                            break;

                    }
                }
                tabs[0].refresh(dat[0], 0);
                tabitem.Content = tabs[tabCont];
            }
            reader.Close();

            createFilters();

            setMenu();

        }

        private void save_Click(object sender, RoutedEventArgs e)
        {
            bool filename = true;
            if (SourceFile == "")
            {
                filename = false;
                SaveFileDialog open = new SaveFileDialog();
                open.DefaultExt = ".miv";
                open.AddExtension = true;
                filename = open.ShowDialog().Value;
                if (filename)
                    SourceFile = open.FileName;
            }

            if (filename)
            {
                try
                {
                    saveDocument();
                }
                catch
                {
                    MessageBox.Show("Error while saving document");

                }
            }
                

        }

        private void save_as_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog save = new SaveFileDialog();
            save.DefaultExt = ".miv";
            save.AddExtension = true;

            if (save.ShowDialog().Value)
            {
                SourceFile = save.FileName;
                try
                {
                    saveDocument();
                }
                catch
                {
                    MessageBox.Show("Error while saving document");
                }
            }      

        }

        private void new_page_Click(object sender, RoutedEventArgs e)
        {
            tabs[tabsN] = new Tab();
            //panels[tabsN]=new DockPanel();
            tabs[tabsN].HorizontalAlignment = HorizontalAlignment.Stretch;
            tabs[tabsN].VerticalAlignment = VerticalAlignment.Stretch;
            tabs[tabsN].Background = Brushes.Transparent;
            TabItem tab = new TabItem();

            //tabitems[tabsN] = new TabItem();
            tab.Header="Page "+ (tabsN+1);
            tab.Content = tabs[tabsN];
            tabs[tabsN].LastChildFill = true;
            Tabs1.Items.Add(tab);
            Tabs1.SelectedIndex = tabsN;
            tabsN++;
        }

        private void new_visualization_Click(object sender, RoutedEventArgs e)
        {

            

            //TabItem tab = tabitems[Tabs1.SelectedIndex];


            

            //Image imagen = new Image();
            
            //ImageSourceConverter source = new ImageSourceConverter();

            
            //Vis aux = new Vis(source.ConvertFromString("http://rcgp.files.wordpress.com/2009/05/notas-musicales3.jpg") as ImageSource);

            //Vis aux = new Vis(dat);
            

            //imagen.Source = (source.ConvertFromString("http://rcgp.files.wordpress.com/2009/05/notas-musicales3.jpg") as ImageSource);

            //imagen.Height = 200;

            /*Button boton = new Button();

            boton.Content = "boton de prueba";

            boton.Width = 150;
            boton.Height = 50;*/

            //DockPanel panel = new DockPanel();
            //panel.Children.Add(imagen);
            //visualizations[cont] = new DockPanel();

            /*Border borde = new Border();

            borde.Background = Brushes.Blue;

            borde.Height = 20;*/

            //DockPanel.SetDock(borde, Dock.Top);

            //visualizations[cont].Children.Add(borde);

            //DockPanel.SetDock(imagen, Dock.Top);

            //visualizations[cont].Children.Add(imagen);

            //visualizations[cont].Background = Brushes.Yellow;

            //borde.ContextMenu.
            

            //código de prueba
            /*
            switch (cont)
            {
                case 0:
                    //DockPanel.SetDock(panel, Dock.Top);
                    DockPanel.SetDock(visualizations[cont], Dock.Left);
                    break;
                case 1:
                    //DockPanel.SetDock(panel, Dock.Top);
                    DockPanel.SetDock(visualizations[cont], Dock.Right);
                    break;
                case 2:
                    DockPanel.SetDock(visualizations[cont], Dock.Bottom);
                    break;
            }*/
            //DockPanel.SetDock(visualizations[cont], Dock.Bottom);
            //visualizations[cont].MaxWidth = panels[Tabs1.SelectedIndex].Width / 2;
          
            //tab.Content = panel;

            //Tabs1.SelectedItem = tab;

            //tabitems[Tabs1.SelectedIndex] = tab;

            //((UIElement)Content).IsEnabled = false;

            loading load = new loading();
            load.Show();
            load.Focus();

            tabs[Tabs1.SelectedIndex].AddVisualization(dat[0], 0, Tabs2.SelectedIndex);

            load.Close();
            //((UIElement)Content).IsEnabled = true;
            //cont++;

            

            /*for (int i = 0; i < dockPanel1.Children.Count - 1; i++)
            {
                dockPanel1.Children[i].
            }*/
            

            //if(dockPanel1.Children.Count>1)
            
            //DockPanel.SetDock(dockPanel1.Children[dockPanel1.Children.Count - 2], Dock.Bottom);

            //dockPanel1.Children.

        
            
        }

        private void print_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog print = new PrintDialog();

            print.UserPageRangeEnabled = true;

            if (!print.ShowDialog().Value)
                return;
            
            print.MinPage = 1;
            print.MaxPage = Convert.ToUInt16(tabsN);

            for (int i = print.PageRange.PageFrom - 1; i <= print.PageRange.PageTo - 1; i++)
                print.PrintVisual((tabs[i] as DockPanel), "Page " + (i + 1).ToString());



        }

        private void load_cel_Click(object sender, RoutedEventArgs e)
        {
            if (path == "")
            {
                StreamReader pathReader = new StreamReader(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\config.config");
                path = pathReader.ReadToEnd();
                path = path.Trim().Replace("\n", "").Replace("\r", "");
                pathReader.Close();
            }

            if (path.Length < 3)
            {
                Configuration config = new Configuration();
                config.ShowDialog();
                if (config.getCanceled())
                    return;

                StreamWriter pathWriter = new StreamWriter(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).Replace("\\bin\\Debug", "\\Resources\\config.config"));
                pathWriter.Write(path);
                pathWriter.Close();
            }

            string current = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            OpenFileDialog open = new OpenFileDialog();
            open.Title = "Select Cel Files List";
            open.ShowDialog();

            try
            {

                StreamReader trier = new StreamReader(open.FileName);
            }
            catch
            {
                return;
            }

            string s = open.FileName;

            StreamReader reader;

            string directory = "";

            try
            {
                directory = System.IO.Path.GetDirectoryName(s);
            
                reader = new StreamReader(s);
            }
            catch
            {
                return;
            }


            string fullCelList = reader.ReadToEnd();

            fullCelList.Trim();

            string [] fullCellArray = fullCelList.Split('\n');

            string aux = "";

            bool isAFile = false;
            for (int i = 0; !isAFile; i++)
            {
                if (i == fullCellArray.Length)
                {
                    MessageBox.Show("Cel files list had not a valid format. Data files weren't loaded");
                    return;
                }

                isAFile = true;

                aux = fullCellArray[i].Trim();

                try
                {
                    reader = new StreamReader(aux);
                }
                catch
                {
                    //MessageBox.Show("uno que no");
                    isAFile = false;
                }
            }



            //aux = reader.ReadLine();

            //aux = aux.Trim();

            //reader = new StreamReader(aux);

            //MessageBox.Show(aux);

             

            bool ext0=false, ext1 = false, ext2 = false, ext3=false;

            int cont = 0;


            while (!ext3)
            {

                try
                {
                    aux = reader.ReadLine();
                }
                catch
                {
                    MessageBox.Show("The program couldn't get the needed CDF File");
                    break;
                }


                for (cont = 0; !ext3 && cont < aux.Length; cont++)
                {
                    //MessageBox.Show(aux[cont].ToString());

                    if (ext2)
                        if (aux[cont] == 'q')
                            ext3 = true;
                        else
                        {
                            ext2 = false;
                            ext1 = false;
                            ext0 = false;
                        }
                    else
                        if (ext1)
                            if (aux[cont] == 's')
                                ext2 = true;
                            else
                            {
                                ext1 = false;
                                ext0 = false;
                            }

                        else
                            if (ext0)

                                if (aux[cont] == '1')
                                    ext1 = true;
                                else
                                {
                                    ext0 = false;
                                }

                            else
                                if (aux[cont] == '.')
                                    ext0 = true;

                }

            }

            cont--;

            //MessageBox.Show(aux[cont].ToString());

            int lenght = 0;

            for (; aux[cont] != ' ' && aux[cont] != '\t'; cont--, lenght++) ;

            lenght = lenght - 4;

            //MessageBox.Show(lenght.ToString());

            cont ++;

            string file = aux[cont].ToString();

            //MessageBox.Show(file);

            for (int l = 1; l < lenght; l++)
            {

                file = string.Concat(file, aux[cont + l].ToString());
                //MessageBox.Show(file);
            }

            file = string.Concat(file, ".CDF");

            //MessageBox.Show(file);








            /*OpenFileDialog CDF_File = new OpenFileDialog();
            CDF_File.Title = "Select CDF File";
            CDF_File.ShowDialog();*/

            //string cdf = CDF_File.FileName;
            string directory_ = current.Replace("\\bin\\Debug", "") + "\\lib\\";
            string cdf = current.Replace("\\bin\\Debug", "") + "\\lib\\" + file;

            cdf = path + "\\" + file;

            cdf = cdf.Replace("CDF", "cdf");
            
            if (!System.IO.File.Exists(cdf))
            {

                MessageBox.Show("CDF file was not found and has to be downloaded from Affymetrix website");

                if (!downloadCDF(cdf))
                    return;

                //OpenFileDialog opencdf = new OpenFileDialog();

                //if (!opencdf.ShowDialog().Value)
                //{
                    /*NETAFFXDOWNLOADMAILSVRLib.NetAffxDownloadEMailSvrClass downloader = new NETAFFXDOWNLOADMAILSVRLib.NetAffxDownloadEMailSvrClass();
                    neta
                    */

                  //  return;
                //}

                //cdf = opencdf.FileName;
            }

            //MessageBox.Show(current.Replace("\\bin\\Debug",""));

            //System.IO.File.Copy(cdf, System.IO.Path.Combine(directory,file), true);

            //cdf = System.IO.Path.Combine(directory, file);

            //MessageBox.Show(cdf);

            Cursor = Cursors.Wait;


            //MessageBox.Show(current);
            loading load = new loading();
            load.Show();
            
/////////////

            BackgroundWorker worker = new BackgroundWorker();

            try
            {
                
                AffymetrixParser.Parse("rma-sketch", s, cdf, current + "/temp");
            }
            catch
            {
                MessageBox.Show("Cel files list had not a valid format. Data files weren't loaded");
                return;
            }
            load.Close();
            string tabulated = current + "/temp/rma-sketch.summary.txt";

            //MessageBox.Show(tabulated);

            /*OpenFileDialog tabFile = new OpenFileDialog();
            tabFile.Title = "Select Tabulated File";
            tabFile.ShowDialog();

            string tabulated = tabFile.FileName;*/

            try
            {
                dat[ndat] = new data(tabulated);
            }
            catch
            {
                MessageBox.Show("Error while loading data: wrong file?");
                return;
            }

            if (dat[0].getNtables() == 0)
                return;

            Cursor = Cursors.Arrow;

            
            //////////////// inicialización de filtros

            try
            {
                DockPanel panel = new DockPanel();

                filterPanels[ndat] = new DockPanel();
                filterPanels[ndat].HorizontalAlignment = HorizontalAlignment.Stretch;
                filterPanels[ndat].VerticalAlignment = VerticalAlignment.Stretch;
                filterPanels[ndat].LastChildFill = false;

                TabItem tabitem = new TabItem();
                Tab tab = new Tab();
                tabitem.Header = "Table " + (ndat + 1);
                tab.Children.Add(panel);
                tabitem.Content = tab;

                tabitem.VerticalAlignment = VerticalAlignment.Stretch;
                tabitem.HorizontalAlignment = HorizontalAlignment.Stretch;
                tabitem.IsSelected = true;

                tab.Background = Brushes.Transparent;
                tab.HorizontalAlignment = HorizontalAlignment.Stretch;
                tab.VerticalAlignment = VerticalAlignment.Stretch;

                tab.Children.Add(filterPanels[ndat]);

                Tabs2.Items.Add(tabitem);
                Tabs2.SelectedIndex = ndat;

                

                

                for (int i = 1; i < dat[ndat].getnCols(); i++)
                {

                    RangeSlider prueba = new RangeSlider();

                    prueba.RangeStart = Convert.ToInt64(dat[ndat].getLeft(i - 1) * 10000);
                    prueba.RangeStartSelected = prueba.RangeStart;
                    prueba.RangeStop = Convert.ToInt64(dat[ndat].getRight(i - 1) * 10000);
                    prueba.RangeStopSelected = prueba.RangeStop;
                    prueba.MinHeight = 20;
                    prueba.Name = dat[ndat].getColumnTittle(0, i).Replace("-", "guionalto");
                    RegisterEvents(prueba);

                    //prueba.ToolTip = dat.getleft
                    prueba.ToolTip = prueba.RangeStartSelected.ToString() + " - " + prueba.RangeStopSelected.ToString();
                    //prueba.

                    

                    if (prueba.RangeStart != prueba.RangeStop)
                    {
                        TextBlock text = new TextBlock();
                        text.Text = dat[ndat].getColumnTittle(0, i);

                        DockPanel.SetDock(text, Dock.Top);

                        filterPanels[ndat].Children.Add(text);

                        DockPanel.SetDock(prueba, Dock.Top);

                        filterPanels[ndat].Children.Add(prueba);


                    }




                }

                countSelected.Content = dat[0].getNSelected().ToString() + " genes selected";

                DockPanel.SetDock(countSelected, Dock.Bottom);

                filterPanels[0].Children.Add(countSelected);
            }

            catch
            {
                MessageBox.Show("Error while creating filters: Wrong file?");
                return;
            }

            //load_experiment_design();

            ndat++;












            /*
            try
            {
                //Pass the file path and file name to the StreamReader constructor
                StreamReader sr = new StreamReader(tabulated);

                //Read the first line of text
                line = sr.ReadLine();
                sr.read*******

                //Continue to read until you reach end of file
                while (line != null)
                {
                    //write the lie to console window
                    Console.WriteLine(line);
                    //Read the next line
                    line = sr.ReadLine();
                }

                //close the file
                sr.Close();
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            */

            //


            new_visualization.IsEnabled = true;
            save.IsEnabled = true;
            save_as.IsEnabled = true;
            CreateTable.IsEnabled = true;
            new_page.IsEnabled = true;
            print.IsEnabled = true;
            Calculations.IsEnabled = true;
            Show_Table.IsEnabled = true;
            Exp_Design.IsEnabled = true;

            FileToolBar.Visibility = Visibility.Visible;
            VisToolBar.Visibility = Visibility.Visible;

            loadData_tab.IsEnabled = false;
            calculation_tab.IsEnabled = true;
            transformation_tab.IsEnabled = true;
            visualization_tab.IsEnabled = true;

        }



        private void load_txt_Click(object sender, RoutedEventArgs e)
        {
            /*string current = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            OpenFileDialog open = new OpenFileDialog();
            open.Title = "Select Cel Files List";
            open.ShowDialog();

            string s = open.FileName;

            OpenFileDialog CDF_File = new OpenFileDialog();
            CDF_File.Title = "Select CDF File";
            CDF_File.ShowDialog();

            string cdf = CDF_File.FileName;*/

            //MessageBox.Show(s);

            //AffymetrixParser.Parse("rma-sketch", s, cdf, current+"/temp");
            


            OpenFileDialog tabFile = new OpenFileDialog();
            tabFile.Title = "Select Tabulated File";
            tabFile.ShowDialog();



            try
            {

                StreamReader trier = new StreamReader(tabFile.FileName);
            }
            catch
            {
                return;
            }

            string tabulated = tabFile.FileName;

            //MessageBox.Show(tabulated);

            try
            {
                dat[ndat] = new data(tabulated);
            }
            catch
            {
                MessageBox.Show("Error while loading data: wrong file?");
                return;
            }

            if (dat[0].getNtables() == 0)
                return;

            try
            {

                filterPanels[ndat] = new DockPanel();

                filterPanels[ndat].HorizontalAlignment = HorizontalAlignment.Stretch;
                filterPanels[ndat].VerticalAlignment = VerticalAlignment.Stretch;
                filterPanels[ndat].LastChildFill = false;

                TabItem tabitem = new TabItem();
                Tab tab = new Tab();
                tabitem.Header = "Table " + (ndat + 1);
                tab.Children.Add(filterPanels[ndat]);
                tabitem.Content = tab;

                tabitem.VerticalAlignment = VerticalAlignment.Stretch;
                tabitem.HorizontalAlignment = HorizontalAlignment.Stretch;
                tabitem.IsSelected = true;

                tab.Background = Brushes.Transparent;
                tab.HorizontalAlignment = HorizontalAlignment.Stretch;
                tab.VerticalAlignment = VerticalAlignment.Stretch;


                Tabs2.Items.Add(tabitem);
                Tabs2.SelectedIndex = ndat;

                for (int i = 1; i < dat[ndat].getnCols(); i++)
                {

                    RangeSlider prueba = new RangeSlider();

                    prueba.RangeStart = Convert.ToInt64(dat[ndat].getLeft(i - 1) * 10000) - 1;
                    prueba.RangeStartSelected = prueba.RangeStart;
                    prueba.RangeStop = Convert.ToInt64(dat[ndat].getRight(i - 1) * 10000);
                    prueba.RangeStopSelected = prueba.RangeStop;
                    prueba.MinHeight = 20;
                    prueba.Name = dat[ndat].getColumnTittle(0, i).Replace("-", "guionalto").Replace("/", "_");
                    RegisterEvents(prueba);

                    //prueba.ToolTip = dat.getleft
                    prueba.ToolTip = prueba.RangeStartSelected.ToString() + " - " + prueba.RangeStopSelected.ToString();
                    //prueba.

                    if (prueba.RangeStart != prueba.RangeStop)
                    {
                        TextBlock text = new TextBlock();
                        text.Text = dat[ndat].getColumnTittle(0, i);

                        DockPanel.SetDock(text, Dock.Top);

                        filterPanels[ndat].Children.Add(text);

                        DockPanel.SetDock(prueba, Dock.Top);

                        filterPanels[ndat].Children.Add(prueba);


                    }








                    /***************************
                     * 
                     * Pruebas con la otra librería de Slider Range Selectors. No funciona





                    CustomRangeSelectorControl.RangeSelectorControl f = new CustomRangeSelectorControl.RangeSelectorControl();
                    f.Name = "filter_" + i.ToString();

                    f.BackColor = System.Drawing.SystemColors.Control;
                    f.DelimiterForRange = ",";
                    f.DisabledBarColor = System.Drawing.Color.Gray;
                    f.DisabledRangeLabelColor = System.Drawing.Color.Gray;
                    f.GapFromLeftMargin = ((uint)(15u));
                    f.GapFromRightMargin = ((uint)(15u));
                    f.HeightOfThumb = 20F;
                    f.InFocusBarColor = System.Drawing.Color.DarkViolet;
                    f.InFocusRangeLabelColor = System.Drawing.Color.Indigo;
                    f.LabelFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
                    f.LeftThumbImagePath = null;
                    //f.Location = new System.Drawing.Point(14, 19);
                    f.MiddleBarWidth = ((uint)(2u));
                    f.OutputStringFontColor = System.Drawing.Color.Black;
                    f.RangeString = "Range";
                    f.RightThumbImagePath = null;
                    f.Size = new System.Drawing.Size(165, 80);
                    f.TabIndex = 0;
                    f.ThumbColor = System.Drawing.Color.Black;
                    f.WidthOfThumb = 10F;
                
                    //f.DelimiterForRange = "-";
                    f.RangeValues = dat.values(i-1, 50);

                    MessageBox.Show(dat.values(i-1,50));
 
                    f.Range1 = dat.getMin(i - 1).ToString();
                    f.Range1 = f.Range1.Replace(',', '.');
                    f.Range2 = dat.getMax(i-1).ToString();
                    f.Range2 = f.Range2.Replace(',', '.');
                
                
                    //addFilter(f, panel);
                     * 
                     **/




                }
                countSelected.Content = dat[0].getNSelected().ToString() + " genes selected";

                DockPanel.SetDock(countSelected, Dock.Bottom);

                filterPanels[0].Children.Add(countSelected);

            }

            catch
            {
                MessageBox.Show("Error while creating filters: Wrong file?");
                return;
            }

            /*
            try
            {
                //Pass the file path and file name to the StreamReader constructor
                StreamReader sr = new StreamReader(tabulated);

                //Read the first line of text
                line = sr.ReadLine();
                sr.read*******

                //Continue to read until you reach end of file
                while (line != null)
                {
                    //write the lie to console window
                    Console.WriteLine(line);
                    //Read the next line
                    line = sr.ReadLine();
                }

                //close the file
                sr.Close();
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            */

            //

            //load_experiment_design();

            ndat++;

            new_visualization.IsEnabled = true;
            save.IsEnabled = true;
            save_as.IsEnabled = true;
            CreateTable.IsEnabled = true;
            new_page.IsEnabled = true;
            print.IsEnabled = true;
            Calculations.IsEnabled = true;
            Show_Table.IsEnabled = true;
            Exp_Design.IsEnabled = true;

            FileToolBar.Visibility = Visibility.Visible;
            VisToolBar.Visibility = Visibility.Visible;

            loadData_tab.IsEnabled = false;
            calculation_tab.IsEnabled = true;
            transformation_tab.IsEnabled = true;
            visualization_tab.IsEnabled = true;

        }

        private void Tabs1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selectedTab = Tabs1.SelectedIndex;
        }

        public void addFilter(CustomRangeSelectorControl.RangeSelectorControl f, DockPanel p)
        {
            GroupBox aux = new GroupBox();
            aux.Content = f;
            f.Show();
            //aux.Location = new System.Drawing.Point(12, 234);
            aux.Name = "groupBox5";
            aux.HorizontalAlignment = HorizontalAlignment.Stretch;
            aux.Width = 200;
            aux.Height = 90;
            //aux.VerticalAlignment = VerticalAlignment.Top;
            aux.TabIndex = 13;
            
            aux.Header = "pruebas";

            DockPanel.SetDock(aux, Dock.Top);
            //tabs[Tabs1.SelectedIndex].Children.Add(aux);
            p.Children.Add(aux);

        }


        
        void RegisterEvents(RangeSlider Filter)
        {

            /*Filter.MouseEnter += new MouseEventHandler(Filter_MouseEnterEvent);

            Filter.MouseLeave += new MouseEventHandler(Filter_MouseLeaveEvent);

            Filter.MouseLeftButtonDown += new MouseButtonEventHandler(Filter_MouseLeftButtonDownEvent);

            Filter.MouseLeftButtonUp += new MouseButtonEventHandler(Filter_MouseLeftButtonUpEvent);

            Filter.MouseMove += new MouseEventHandler(Filter_MouseMoveEvent);*/

            Filter.RangeSelectionChanged += RangeSliderRangeSelectionChanged;

            
        }

        private void Filter_MouseEnterEvent(object sender, MouseEventArgs e) {
            
        }
        private void Filter_MouseLeaveEvent(object sender, MouseEventArgs e) {
            
        }
        private void Filter_MouseLeftButtonDownEvent(object sender, MouseButtonEventArgs e)
        {
            
            dat[Tabs2.SelectedIndex].changeClick(this.Name);
        }
        private void Filter_MouseLeftButtonUpEvent(object sender, MouseButtonEventArgs e) 
        {
            
            dat[Tabs2.SelectedIndex].changeClick(this.Name);
        }
        private void Filter_MouseMoveEvent(object sender, MouseEventArgs e) 
        {
            //((RangeSlider)sender).ranges
            
            //if (dat.getClick(Name))
            
            
        }

        private void RangeSliderRangeSelectionChanged(object sender, RangeSelectionChangedEventArgs e)
        {
            
            ((RangeSlider)sender).RangeStartSelected = e.NewRangeStart;
            ((RangeSlider)sender).RangeStopSelected = e.NewRangeStop;
            
            dat[Tabs2.SelectedIndex].setFilter(((RangeSlider)sender).Name, (e.NewRangeStart-1) / 10000.0, (e.NewRangeStop+1) / 10000.0);
            ((RangeSlider)sender).ToolTip = ((RangeSlider)sender).RangeStartSelected.ToString() + " - " + ((RangeSlider)sender).RangeStopSelected.ToString();
            //MessageBox.Show("si");

            dat[Tabs2.SelectedIndex].refreshFilters();
            for (int i = 0; i < tabsN; i++)
            {
                tabs[i].refresh(dat[Tabs2.SelectedIndex], Tabs2.SelectedIndex);
            }

            countSelected.Content = dat[0].getNSelected().ToString() + " genes selected";

        }

        private void histogram_Click(object sender, RoutedEventArgs e)
        {
            tabs[Tabs1.SelectedIndex].AddVisualization(dat[Tabs2.SelectedIndex], 0, Tabs2.SelectedIndex);
        }

        private void clustering_Click(object sender, RoutedEventArgs e)
        {

            tabs[Tabs1.SelectedIndex].AddVisualization(dat[Tabs2.SelectedIndex], 1, Tabs2.SelectedIndex);
        }

        private void scatterplot_Click(object sender, RoutedEventArgs e)
        {
            
            
            tabs[Tabs1.SelectedIndex].AddVisualization(dat[Tabs2.SelectedIndex], 2, Tabs2.SelectedIndex);
            
            
        }

        private void heatMap_Click(object sender, RoutedEventArgs e)
        {
            if (!dat[0].isCreated(2))
            {
                MessageBox.Show("Correlation matrix has not been created and will be created now");
                dat[0].createCorrelationMatrix();
            }
            tabs[Tabs1.SelectedIndex].AddVisualization(dat[Tabs2.SelectedIndex], 3, Tabs2.SelectedIndex);
        }

        private void boxPlot_Click(object sender, RoutedEventArgs e)
        {
            tabs[Tabs1.SelectedIndex].AddVisualization(dat[Tabs2.SelectedIndex], 4, Tabs2.SelectedIndex);
        }

        private void lineGraphic_Click(object sender, RoutedEventArgs e)
        {
            tabs[Tabs1.SelectedIndex].AddVisualization(dat[Tabs2.SelectedIndex], 5, Tabs2.SelectedIndex);
        }

        private void load_experiment_design()
        {
            OpenFileDialog design = new OpenFileDialog();
            design.Title = "Load experiment design file";
            design.ShowDialog();

            string e_design = design.FileName;

            dat[Tabs2.SelectedIndex].load_experiment_design(e_design);

            
        }

        private void Tabs2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void document_MouseDown(object sender, MouseButtonEventArgs e)
        {
            /*if (ndat>0)
                if ((Tabs1.SelectedItem as TabItem).IsMouseOver)
                {
                    tabs[Tabs1.SelectedIndex].click(dat[Tabs2.SelectedIndex], e);
                    //MessageBox.Show("Hola");
                }*/
        }

        private void document_MouseUp(object sender, MouseButtonEventArgs e)
        {

        }

        public void prueba()
        {
            MessageBox.Show(dat[Tabs2.SelectedIndex].markingIndex[0].ToString());
            MessageBox.Show(dat[Tabs2.SelectedIndex].markingIndex[1].ToString());
        }

        public void setMarkingIndex(int n, int i)
        {
            dat[Tabs2.SelectedIndex].markingIndex[n] = i;
        }

        public static void updateFilters(int n)
        {
            
            //Tabs2.SelectedIndex = n;
            for (int i = 0; i < 2; i++)
            {
                if (Convert.ToInt64(dat[n].markingMin[i] * 10000) < (filterPanels[n].Children[dat[n].markingIndex[i] * 2 + 1] as RangeSlider).RangeStart)
                    (filterPanels[n].Children[dat[n].markingIndex[i] * 2 + 1] as RangeSlider).RangeStartSelected = (filterPanels[n].Children[dat[n].markingIndex[i] * 2 + 1] as RangeSlider).RangeStart+1;
                else
                    (filterPanels[n].Children[dat[n].markingIndex[i]*2+1] as RangeSlider).RangeStartSelected = Convert.ToInt64(dat[n].markingMin[i]*10000);
                if (Convert.ToInt64(dat[n].markingMax[i] * 10000) > (filterPanels[n].Children[dat[n].markingIndex[i] * 2 + 1] as RangeSlider).RangeStop)
                    (filterPanels[n].Children[dat[n].markingIndex[i] * 2 + 1] as RangeSlider).RangeStopSelected = (filterPanels[n].Children[dat[n].markingIndex[i] * 2 + 1] as RangeSlider).RangeStop;
                else
                    (filterPanels[n].Children[dat[n].markingIndex[i]*2+1] as RangeSlider).RangeStopSelected = Convert.ToInt64(dat[n].markingMax[i]*10000);
                
                dat[n].setFilter((filterPanels[n].Children[dat[n].markingIndex[i]*2+1] as RangeSlider).Name, (filterPanels[n].Children[dat[n].markingIndex[i]*2+1] as RangeSlider).RangeStartSelected / 10000.0, (filterPanels[n].Children[dat[n].markingIndex[i]*2+1] as RangeSlider).RangeStopSelected / 10000.0);
                (filterPanels[n].Children[dat[n].markingIndex[i]*2+1] as RangeSlider).ToolTip = (filterPanels[n].Children[dat[n].markingIndex[i]*2+1] as RangeSlider).RangeStartSelected.ToString() + " - " + (filterPanels[n].Children[dat[n].markingIndex[i]*2+1] as RangeSlider).RangeStopSelected.ToString();

                
            }

            dat[n].refreshFilters();

            for (int j = 0; j < tabsN; j++)
            {
                tabs[j].refresh(dat[n], n);
            }
        }

        public void pruebas()
        {
            int n = Tabs2.SelectedIndex;
            for (int j = 0; j < tabsN; j++)
            {
                tabs[j].refresh(dat[n], n);
            }
        }

        private void Tools_Click(object sender, RoutedEventArgs e)
        {
            //downloadCDF("prueba");
        }

        private void Normalize_Data(object sender, RoutedEventArgs e)
        {
            int n = Tabs2.SelectedIndex;
            if (!dat[n].isCreated(1))
            {
                dat[n].normalizeData();
                for (int i = 0; i < tabsN; i++)
                    tabs[i].refreshCombos(dat[n]);
            }
        }

        private void select_cel_click(object sender, RoutedEventArgs e)
        {
            selectCel select = new selectCel();
            select.ShowDialog();
            if (select.getSelected())
            {
                load_celList(select.getCelList());
            }

        }

        private void load_celList(string s)
        {

            string current = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            string directory = System.IO.Path.GetDirectoryName(s);

            StreamReader reader = new StreamReader(s);
            MessageBox.Show(s);
            string aux = reader.ReadLine();

            aux = reader.ReadLine();

            aux = aux.Trim();

            reader = new StreamReader(aux);

            bool ext0 = false, ext1 = false, ext2 = false, ext3 = false;

            int cont = 0;


            while (!ext3)
            {
                aux = reader.ReadLine();


                for (cont = 0; !ext3 && cont < aux.Length; cont++)
                {

                    if (ext2)
                        if (aux[cont] == 'q')
                            ext3 = true;
                        else
                        {
                            ext2 = false;
                            ext1 = false;
                            ext0 = false;
                        }
                    else
                        if (ext1)
                            if (aux[cont] == 's')
                                ext2 = true;
                            else
                            {
                                ext1 = false;
                                ext0 = false;
                            }

                        else
                            if (ext0)

                                if (aux[cont] == '1')
                                    ext1 = true;
                                else
                                {
                                    ext0 = false;
                                }

                            else
                                if (aux[cont] == '.')
                                    ext0 = true;

                }

            }

            cont--;

            int lenght = 0;

            for (; aux[cont] != ' ' && aux[cont] != '\t'; cont--, lenght++) ;

            lenght = lenght - 4;

            cont++;

            string file = aux[cont].ToString();

            for (int l = 1; l < lenght; l++)
            {

                file = string.Concat(file, aux[cont + l].ToString());
            }

            file = string.Concat(file, ".CDF");

            string cdf = current + "/lib/" + file;

            System.IO.File.Copy(cdf, System.IO.Path.Combine(directory, file), true);

            cdf = System.IO.Path.Combine(directory, file);

            Cursor = Cursors.Wait;

            loading load = new loading();
            load.Show();
            AffymetrixParser.Parse("rma-sketch", s, cdf, current + "/temp");
            load.Close();
            string tabulated = current + "/temp/rma-sketch.summary.txt";

            dat[ndat] = new data(tabulated);

            Cursor = Cursors.Arrow;

            //////////////// inicialización de filtros


            DockPanel panel = new DockPanel();

            panel.HorizontalAlignment = HorizontalAlignment.Stretch;
            panel.VerticalAlignment = VerticalAlignment.Stretch;
            panel.LastChildFill = false;

            TabItem tabitem = new TabItem();
            Tab tab = new Tab();
            tabitem.Header = "Table " + (ndat + 1);
            tab.Children.Add(panel);
            tabitem.Content = tab;

            tabitem.VerticalAlignment = VerticalAlignment.Stretch;
            tabitem.HorizontalAlignment = HorizontalAlignment.Stretch;
            tabitem.IsSelected = true;

            tab.Background = Brushes.Transparent;
            tab.HorizontalAlignment = HorizontalAlignment.Stretch;
            tab.VerticalAlignment = VerticalAlignment.Stretch;


            Tabs2.Items.Add(tabitem);
            Tabs2.SelectedIndex = ndat;

            for (int i = 1; i < dat[ndat].getnCols(); i++)
            {

                RangeSlider prueba = new RangeSlider();

                prueba.RangeStart = Convert.ToInt64(dat[ndat].getLeft(i - 1) * 10000);
                prueba.RangeStartSelected = prueba.RangeStart;
                prueba.RangeStop = Convert.ToInt64(dat[ndat].getRight(i - 1) * 10000);
                prueba.RangeStopSelected = prueba.RangeStop;
                prueba.MinHeight = 20;
                prueba.Name = dat[ndat].getColumnTittle(0, i).Replace("-", "guionalto");
                RegisterEvents(prueba);

                //prueba.ToolTip = dat.getleft
                prueba.ToolTip = prueba.RangeStartSelected.ToString() + " - " + prueba.RangeStopSelected.ToString();
                //prueba.

                if (prueba.RangeStart != prueba.RangeStop)
                {
                    TextBlock text = new TextBlock();
                    text.Text = dat[ndat].getColumnTittle(0, i);

                    DockPanel.SetDock(text, Dock.Top);

                    panel.Children.Add(text);

                    DockPanel.SetDock(prueba, Dock.Top);

                    panel.Children.Add(prueba);


                }
            }

            ndat++;
            new_visualization.IsEnabled = true;
            save.IsEnabled = true;
            save_as.IsEnabled = true;
            CreateTable.IsEnabled = true;
            new_page.IsEnabled = true;
            print.IsEnabled = true;
            Calculations.IsEnabled = true;
            Show_Table.IsEnabled = true;
            Exp_Design.IsEnabled = true;

            FileToolBar.Visibility = Visibility.Visible;
            VisToolBar.Visibility = Visibility.Visible;

            loadData_tab.IsEnabled = false;
            calculation_tab.IsEnabled = true;
            transformation_tab.IsEnabled = true;
            visualization_tab.IsEnabled = true;
        }

        private void CorrelationMatrix_Click(object sender, RoutedEventArgs e)
        {
            dat[0].createCorrelationMatrix();

        }

        private void Anova_Click(object sender, RoutedEventArgs e)
        {



        }

        private void Calculate_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                R_Application rApp = new R_Application();



                OpenFileDialog open = new OpenFileDialog();
                open.Title = "Select R File";

                if (!open.ShowDialog().Value)
                    return;

                string file = open.FileName;

                if (rApp.calculate(file))
                {
                    try
                    {
                        RangeSlider prueba = new RangeSlider();

                        try
                        {
                            prueba.RangeStart = Convert.ToInt64(dat[0].getLeft(dat[0].getnFilters() - 1) * 10000);
                            prueba.RangeStartSelected = prueba.RangeStart;
                            prueba.RangeStop = Convert.ToInt64(dat[0].getRight(dat[0].getnFilters() - 1) * 10000);
                            prueba.RangeStopSelected = prueba.RangeStop;
                            prueba.MinHeight = 20;
                        }
                        catch
                        {
                            MessageBox.Show("Error while setting rangestart or rangestop");
                            return;
                        }
                        try
                        {
                            prueba.Name = dat[0].getColumnTittle(0, dat[0].getnFilters() - 1).Replace("-", "guionalto");
                        }
                        catch
                        {
                            MessageBox.Show("Error while setting slider name");
                            return;
                        }
                        try
                        {
                            RegisterEvents(prueba);
                        }
                        catch
                        {
                            MessageBox.Show("Error while registering slider events");
                            return;
                        }
                        //prueba.ToolTip = dat.getleft
                        try
                        {
                            prueba.ToolTip = prueba.RangeStartSelected.ToString() + " - " + prueba.RangeStopSelected.ToString();
                        }
                        catch
                        {
                            MessageBox.Show("Error while setting slider tooltip");
                            return;
                        }
                        //prueba.

                        if (prueba.RangeStart != prueba.RangeStop)
                        {
                            TextBox text = new TextBox();
                            try
                            {
                                text.Text = dat[0].getColumnTittle(0, dat[0].getnCols() - 1);
                            }
                            catch
                            {
                                MessageBox.Show("error while creating textbox");
                                return;
                            }
                            try
                            {
                                DockPanel.SetDock(text, Dock.Top);

                                filterPanels[0].Children.Add(text);
                            }
                            catch
                            {
                                MessageBox.Show("error while adding text box to filters panel");
                                return;
                            }

                            try
                            {
                                DockPanel.SetDock(prueba, Dock.Top);

                                filterPanels[0].Children.Add(prueba);
                            }
                            catch
                            {
                                MessageBox.Show("error while adding slider to filters panel");
                                return;
                            }
                        }
                    }
                    catch
                    {
                        MessageBox.Show("Fatal error while adding new filter");
                        this.Close();
                    }


                    try
                    {
                        addCalculation(file);
                    }

                    catch
                    {
                        MessageBox.Show("the application failed while modiffying configuration files; file won't be available as menu item");
                    }
                }
            }
            catch
            {
                MessageBox.Show("Couldn't initialize R conection. Wrong R installation?");
                return;
            }


        }

        private void Transformate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                R_Application rApp = new R_Application();

                OpenFileDialog open = new OpenFileDialog();
                open.Title = "Select R File";

                if (!open.ShowDialog().Value)
                    return;

                string file = open.FileName;

                if (rApp.Transformate(file))
                {
                    for (int i = 0; i < tabsN; i++)
                        tabs[i].refreshCombos(dat[0]);
                    addTransformation(file);
                }
            }
            catch
            {
                MessageBox.Show("Couldn't initialize R conection. Wrong R installation?");
                return;
            }

        }

        private void Help_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\resources\\manual.pdf");


            System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\manual.pdf");
        }


        public void addTransformation(string file){


            if (!file.Contains(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\"))

            try{
                System.IO.File.Copy(file, System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\"+System.IO.Path.GetFileName(file).Replace(System.IO.Path.GetDirectoryName(file), "").Replace("\\", ""), true);
            }
            catch{
                return;
            }

            file = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\"+System.IO.Path.GetFileName(file).Replace(System.IO.Path.GetDirectoryName(file), "").Replace("\\", "");

            string file_ = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\transformations.ini";

            StreamReader reader = new StreamReader(file_);

            string [] files = reader.ReadToEnd().Trim().Split('\n');

            reader.Close();

            StreamWriter writer = new StreamWriter(file_);

            for (int i = 0; i< files.Length; i++)
                writer.Write(files[i]+'\n');

            bool different = true;

            for (int i = 0; i < files.Length; i++)

                if (files[i] == file)

                    different = false;

            if (different)
                writer.Write(file);

            //MessageBox.Show(file);

            writer.Close();
        }

        public void addCalculation(string file)
        {


            try{
                if (!System.IO.File.Exists(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\"+System.IO.Path.GetFileName(file).Replace(System.IO.Path.GetDirectoryName(file), "").Replace("\\", "")))
                    System.IO.File.Copy(file, System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\" + System.IO.Path.GetFileName(file).Replace(System.IO.Path.GetDirectoryName(file), "").Replace("\\", ""), true);
            }
            catch{
                MessageBox.Show("Error while copying R file");
                return;
            }

            file = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\" + System.IO.Path.GetFileName(file).Replace(System.IO.Path.GetDirectoryName(file), "").Replace("\\", "");

            string file_ = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\calculations.ini";

            string[] files;

            try
            {
                StreamReader reader = new StreamReader(file_);

                files = reader.ReadToEnd().Trim().Split('\n');

                reader.Close();

            }

            catch
            {
                MessageBox.Show("Error while reading calculation.ini in addCalculation");
                return;
            }

            StreamWriter writer;

            try
            {
                writer = new StreamWriter(file_);

                for (int i = 0; i < files.Length; i++)
                    writer.Write(files[i] + '\n');
            }
            catch
            {
                MessageBox.Show("Error while writing in calculations.ini in addCalculation");
                return;
            }

            bool different = true;

            for (int i = 0; i < files.Length; i++)

                if (files[i] == file)

                    different = false;
            try
            {
                if (different)
                    writer.Write(file);
                writer.Close();
            }
            catch
            {
                MessageBox.Show("Error while writing new file in calculations.ini in addCalculation");
                return;
            }
            //MessageBox.Show(file);

            
        }


        private void ExistingTransformation(object sender, RoutedEventArgs e)
        {
            try
            {
                StreamReader reader = new StreamReader(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\transformations.ini");
                string[] transformations = reader.ReadToEnd().Trim().Split('\n');

                reader.Close();

                int index = -1;

                for (int i = 0; i < transformations.Length; i++)
                {
                    //MessageBox.Show((sender as MenuItem).Header.ToString() + "\n" + System.IO.Path.GetFileNameWithoutExtension(transformations[i]).Replace(System.IO.Path.GetDirectoryName(transformations[i]), "").Replace("\\", ""));

                    if ((sender as MenuItem).Header.ToString() == System.IO.Path.GetFileNameWithoutExtension(transformations[i]).Replace(System.IO.Path.GetDirectoryName(transformations[i]), "").Replace("\\", ""))
                        index = i;
                }

                if (index != -1)
                {

                    R_Application rApp;
                    try
                    {
                        rApp = new R_Application();
                    }

                    catch
                    {
                        MessageBox.Show("R doesn't seem to work ok. Install it again");
                    }

                    rApp = new R_Application();


                    string file = transformations[index];

                    if (rApp.Transformate(file))
                    {
                        for (int i = 0; i < tabsN; i++)
                            tabs[i].refreshCombos(dat[0]);

                    }
                }

            }
            catch
            {
                MessageBox.Show("File not found: " + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\transformations.ini");
                return;
            }


        }


        public void ExistingCalculation(object sender, RoutedEventArgs e)
        {
            try
            {
                StreamReader reader = new StreamReader(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\calculations.ini");

                string[] transformations = reader.ReadToEnd().Trim().Split('\n');

                reader.Close();

                int index = -1;

                for (int i = 0; i < transformations.Length; i++)
                {
                    //MessageBox.Show((sender as MenuItem).Header.ToString() + "\n" + System.IO.Path.GetFileNameWithoutExtension(transformations[i]).Replace(System.IO.Path.GetDirectoryName(transformations[i]), "").Replace("\\", ""));

                    if ((sender as MenuItem).Header.ToString() == System.IO.Path.GetFileNameWithoutExtension(transformations[i]).Replace(System.IO.Path.GetDirectoryName(transformations[i]), "").Replace("\\", ""))
                        index = i;
                }

                if (index != -1)
                {
                    R_Application rApp = new R_Application();

                    string file = transformations[index];

                    if (rApp.calculate(file))
                    {

                        RangeSlider prueba = new RangeSlider();

                        prueba.RangeStart = Convert.ToInt64(dat[0].getLeft(dat[0].getnFilters() - 1) * 10000);
                        prueba.RangeStartSelected = prueba.RangeStart;
                        prueba.RangeStop = Convert.ToInt64(dat[0].getRight(dat[0].getnFilters() - 1) * 10000);
                        prueba.RangeStopSelected = prueba.RangeStop;
                        prueba.MinHeight = 20;
                        prueba.Name = dat[0].getColumnTittle(0, dat[0].getnFilters() - 1).Replace("-", "guionalto");
                        RegisterEvents(prueba);

                        //prueba.ToolTip = dat.getleft
                        prueba.ToolTip = prueba.RangeStartSelected.ToString() + " - " + prueba.RangeStopSelected.ToString();
                        //prueba.

                        if (prueba.RangeStart != prueba.RangeStop)
                        {
                            TextBlock text = new TextBlock();
                            text.Text = dat[0].getColumnTittle(0, dat[0].getnCols() - 1);

                            DockPanel.SetDock(text, Dock.Top);

                            filterPanels[0].Children.Add(text);

                            DockPanel.SetDock(prueba, Dock.Top);

                            filterPanels[0].Children.Add(prueba);


                        }


                    }
                }
            }
            catch
            {
                MessageBox.Show("File not found: " + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\calculations.ini");
                return;
            }

        }

        public static void bringProgress()
        {

            ;

        }

        private void saveDocument()
        {

            StreamWriter writer = new StreamWriter(SourceFile);

            writer.Write(ndat.ToString() + "\n");

            int aux = 1;

            for (int i = 1; i < 20; i++)
                if (dat[0].isCreated(i)) aux++;

            writer.Write(aux.ToString() + "\n");

            writer.Write(dat[0].getnRows() + "\t" + dat[0].getnCols() + "\n");

            for (int i = 0; i < dat[0].getnCols(); i++)
            {

                if (i == dat[0].getnCols() - 1)
                    writer.Write(dat[0].getColumn(0, i).DataType.Name + "\n");
                else
                    writer.Write(dat[0].getColumn(0, i).DataType.Name + "\t");
            }


            for (int i = 0; i < 20; i++)
            {
                if (dat[0].isCreated(i))
                {

                    writer.Write(dat[0].getTableName(i) + "\n");
                    //MessageBox.Show(aux.ToString());

                    if (dat[0].getTableName(i) != "Correlation Matrix")
                    {
                        for (int j = 0; j < dat[0].getnCols(); j++)
                            if (j == dat[0].getnCols() - 1)
                                writer.Write(dat[0].getColumnTittle(i, j) + "\n");
                            else
                                writer.Write(dat[0].getColumnTittle(i, j) + "\t");
                        for (int j = 0; j < dat[0].getnRows(); j++)
                            for (int l = 0; l < dat[0].getnCols(); l++)
                                if (l == dat[0].getnCols() - 1)
                                    if (l == 0)
                                        writer.Write(dat[0].getRowName(i, j) + "\n");
                                    else
                                        writer.Write(dat[0].getData(i, j, l - 1) + "\n");
                                else
                                    if (l == 0)
                                        writer.Write(dat[0].getRowName(i, j) + "\t");
                                    else
                                        writer.Write(dat[0].getData(i, j, l - 1) + "\t");
                    }
                }
            }
            writer.Write(tabsN + "\n");

            for (int ntab = 0; ntab < tabsN; ntab++)
            {

                writer.Write((Tabs1.Items[ntab] as TabItem).Header.ToString() + "\n");
                writer.Write(tabs[ntab].getNVis() + "\n");

                for (int nvis = 0; nvis < tabs[ntab].getNVis(); nvis++)
                {
                    int type = tabs[ntab].getVis(nvis).getType();
                    writer.Write(type + "\n");

                    switch (type)
                    {

                        case 0:

                            writer.Write(tabs[ntab].getVis(nvis).getNSeries().ToString() + "\t" + tabs[ntab].getVis(nvis).getTableNumber().ToString() + "\n");
                            for (int seriesCont = 0; seriesCont < tabs[ntab].getVis(nvis).getNSeries(); seriesCont++)
                                if (seriesCont + 1 == tabs[ntab].getVis(nvis).getNSeries())
                                    writer.Write(tabs[ntab].getVis(nvis).getSerie(seriesCont) + "\n");
                                else
                                    writer.Write(tabs[ntab].getVis(nvis).getSerie(seriesCont) + "\t");

                            writer.Write(tabs[ntab].getVis(nvis).getNSteps().ToString() + "\n");

                            break;

                        case 1:

                            break;

                        case 2:

                            writer.Write(tabs[ntab].getVis(nvis).getTableNumber().ToString() + "\n");
                            for (int gen = 0; gen < dat[0].getnRows(); gen++)
                                if (gen + 1 == dat[0].getnRows())
                                    writer.Write(tabs[ntab].getVis(nvis).getSerie(gen).ToString() + "\n");
                                else
                                    writer.Write(tabs[ntab].getVis(nvis).getSerie(gen).ToString() + "\t");

                            break;

                        case 3:

                            break;

                        case 4:

                            writer.Write(tabs[ntab].getVis(nvis).getNSeries().ToString() + "\t" + tabs[ntab].getVis(nvis).getTableNumber().ToString() + "\n");
                            for (int group = 0; group < tabs[ntab].getVis(nvis).getNSeries(); group++)
                                if (group + 1 == tabs[ntab].getVis(nvis).getNSeries())
                                    writer.Write(tabs[ntab].getVis(nvis).getSerie(group).ToString() + "\n");
                                else
                                    writer.Write(tabs[ntab].getVis(nvis).getSerie(group).ToString() + "\t");

                            break;

                        case 5:

                            writer.Write(tabs[ntab].getVis(nvis).getNSeries().ToString() + "\t" + tabs[ntab].getVis(nvis).getTableNumber().ToString() + "\n");
                            for (int gen = 0; gen < tabs[ntab].getVis(nvis).getNSeries(); gen++)
                                if (gen + 1 == tabs[ntab].getVis(nvis).getNSeries())
                                    writer.Write(tabs[ntab].getVis(nvis).getSerie(gen).ToString() + "\n");
                                else
                                    writer.Write(tabs[ntab].getVis(nvis).getSerie(gen).ToString() + "\t");



                            break;

                    }
                }
            }

            writer.Close();
        }

        private void createFilters()
        {

            //MessageBox.Show("entra");

            Tabs2 = new TabControl();

            filterPanels = new DockPanel[20];
            filterPanels[0] = new DockPanel();

            filterPanels[0].HorizontalAlignment = HorizontalAlignment.Stretch;
            filterPanels[0].VerticalAlignment = VerticalAlignment.Stretch;
            filterPanels[0].LastChildFill = false;

            TabItem tabitem = new TabItem();
            Tab tab = new Tab();
            tabitem.Header = "Table " + (ndat);
            tab.Children.Add(filterPanels[0]);
            tabitem.Content = tab;

            tabitem.VerticalAlignment = VerticalAlignment.Stretch;
            tabitem.HorizontalAlignment = HorizontalAlignment.Stretch;
            tabitem.IsSelected = true;

            tab.Background = Brushes.Transparent;
            tab.HorizontalAlignment = HorizontalAlignment.Stretch;
            tab.VerticalAlignment = VerticalAlignment.Stretch;


            Tabs2.Items.Add(tabitem);
            Tabs2.SelectedIndex = 0;

            resizingPanel1.Children.Add(Tabs2);

            for (int i = 1; i < dat[0].getnCols(); i++)
            {
                //MessageBox.Show(i.ToString());
                RangeSlider prueba = new RangeSlider();

                prueba.RangeStart = Convert.ToInt64(dat[0].getLeft(i - 1) * 10000) - 1;
                prueba.RangeStartSelected = prueba.RangeStart;
                prueba.RangeStop = Convert.ToInt64(dat[0].getRight(i - 1) * 10000);
                prueba.RangeStopSelected = prueba.RangeStop;
                prueba.MinHeight = 20;
                prueba.Name = dat[0].getColumnTittle(0, i).Replace("-", "_").Replace("/", "_");
                RegisterEvents(prueba);

                //prueba.ToolTip = dat.getleft
                prueba.ToolTip = prueba.RangeStartSelected.ToString() + " - " + prueba.RangeStopSelected.ToString();
                //prueba.
               
                if (prueba.RangeStart != prueba.RangeStop)
                {
                    TextBlock text = new TextBlock();
                    text.Text = dat[0].getColumnTittle(0, i);

                    DockPanel.SetDock(text, Dock.Top);

                    filterPanels[0].Children.Add(text);

                    DockPanel.SetDock(prueba, Dock.Top);

                    filterPanels[0].Children.Add(prueba);


                }
            }

            countSelected.Content = dat[0].getNSelected().ToString() + " genes selected";

            DockPanel.SetDock(countSelected, Dock.Bottom);

            filterPanels[0].Children.Add(countSelected);

        }


        private void setMenu()
        {
            new_visualization.IsEnabled = true;
            save.IsEnabled = true;
            save_as.IsEnabled = true;
            CreateTable.IsEnabled = true;
            new_page.IsEnabled = true;
            print.IsEnabled = true;
            Calculations.IsEnabled = true;
            Show_Table.IsEnabled = true;
            Exp_Design.IsEnabled = true;

            FileToolBar.Visibility = Visibility.Visible;
            VisToolBar.Visibility = Visibility.Visible;

            loadData_tab.IsEnabled = false;
            calculation_tab.IsEnabled = true;
            transformation_tab.IsEnabled = true;
            visualization_tab.IsEnabled = true;
        }

        public int getSelectedIndex()
        {
            return Tabs1.SelectedIndex;
        }

        private void destroyDocument()
        {

            SourceFile = "";
            tabs = new Tab[20];
            tabs[0] = new Tab();
            tabs[0].Background = Brushes.Transparent;
            tabs[0].HorizontalAlignment = HorizontalAlignment.Stretch;
            tabs[0].VerticalAlignment = VerticalAlignment.Stretch;

            while (Tabs1.Items.Count > 1)
                Tabs1.Items.Remove(Tabs1.Items[1]);
            while (Tabs2.Items.Count > 0)
                Tabs2.Items.Remove(Tabs2.Items[0]);

            //tabs[0].Children.Add(DockingManager x);
            page_1.Content = tabs[0];
            //tabitems[0] = page_1;
            tabsN = 1;

            /*Tab aux = new Tab();
            aux.HorizontalAlignment = HorizontalAlignment.Stretch;
            aux.VerticalAlignment = VerticalAlignment.Stretch;
            table_1.Content = aux;*/

            ndat = 0;
            dat = new data[20];
            filterPanels = new DockPanel[20];
            //Npanels=0;
            //tabs[0] = new Tab();

            while (resizingPanel1.Children.Count > 0)
                resizingPanel1.Children.Remove(resizingPanel1.Children[0]);

            HideMenu();
        }

        private void HideMenu()
        {
            new_visualization.IsEnabled = false;
            save.IsEnabled = false;
            save_as.IsEnabled = false;
            CreateTable.IsEnabled = false;
            new_page.IsEnabled = false;
            print.IsEnabled = false;
            Calculations.IsEnabled = false;
            Exp_Design.IsEnabled = false;

            FileToolBar.Visibility = Visibility.Hidden;
            VisToolBar.Visibility = Visibility.Hidden;

            loadData_tab.IsEnabled = true;
            calculation_tab.IsEnabled = false;
            transformation_tab.IsEnabled = false;
            visualization_tab.IsEnabled = false;
        }

        private void Show_Table_Click(object sender, RoutedEventArgs e)
        {

            /*selectTable select = new selectTable(dat[0]);
            
            select.ShowDialog();

            if (!select.result()) return;

            string name = select.tableName();

            int index = 0;

            for (int i = 0; i < 20; i++)
                if (dat[0].isCreated(i))
                    if (dat[0].getTable(i).TableName == name)
                        index = i;*/

            

            tabs[0].AddVisualization(dat[0], 10, 0);

            //showTable.ShowDialog();

        }

        private void Exp_Design_Click(object sender, RoutedEventArgs e)
        {
            Experiment_Design design = new Experiment_Design(dat[0]);
            design.ShowDialog();
            dat[0].load_EsperimentDesign(design);
        }


        private bool downloadCDF(string fileName)
        {

            MessageBox.Show(fileName);

            //NETAFFXDOWNLOADMAILSVRLib.NetAffxDownloadEMailSvrClass server = new NETAFFXDOWNLOADMAILSVRLib.NetAffxDownloadEMailSvrClass();
            GDACNETAFFXLib.GDACNetAffxAnnotationClass server = new GDACNetAffxAnnotationClass();

            GDACNetAffxAnnotationListingClass prueba = new GDACNetAffxAnnotationListingClass();

            /*prueba.UserName = "wenassoyyo84@hotmail.com";
            prueba.Password = "yo84yo";*/

            prueba.DataDirectory = path;

            prueba.ConnectionIdentifier = "UGRANADA1110";

            AffyAccess affy = new AffyAccess("wenassoyyo84@hotmail.com", "yo84yo");

            affy.ShowDialog();

            if (affy.getCanceled())
                return false;

            prueba.UserName = affy.getUser();
            prueba.Password = affy.getPassword();

            int n = prueba.RetrieveAnnotationList();

            GDACNetAffxAnnotation aux = new GDACNetAffxAnnotationClass();

            for (int i = 0; i < prueba.NumAnnotations; i++)
            {

                prueba.GetAnnotation(i, aux);

                //MessageBox.Show(aux.FullPathName);

                if (fileName == aux.FullPathName)
                    if (prueba.RetrieveAnnotationFile(i) == NETAFFX_DOWNLOAD_STATUS_TYPE.DOWNLOAD_FILE_SUCCESS)
                    {
                        MessageBox.Show("CDF File downloaded");
                        if (user != affy.getUser())
                        {
                            user = affy.getUser();
                            pass = affy.getPassword();
                            StreamWriter writer = new StreamWriter(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "") + "\\..\\..\\Resources\\netaffxLogin.txt");
                            writer.Write(user + "\n");
                            for (int l = 0; l < pass.Length; l++)
                            {
                                Random random = new Random();
                                for (int j = 0; j < 3; j++)
                                {
                                    int num = random.Next(48, 122);
                                    writer.Write(Convert.ToChar(num));
                                }
                                writer.Write(pass[l]);
                            }
                            writer.Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Unable to download CDF File");
                        return false;
                    }
            }

            

            /*if (prueba.RetrieveAnnotationFile(0) == NETAFFX_DOWNLOAD_STATUS_TYPE.DOWNLOAD_FILE_SUCCESS)
                MessageBox.Show(prueba.ToString());*/

            return true;

        }

        private void AnyTableHeatMap_Click(object sender, RoutedEventArgs e)
        {

            tabs[Tabs1.SelectedIndex].AddVisualization(dat[Tabs2.SelectedIndex], 6, Tabs2.SelectedIndex);
        

            
        }

        public int getSelectedTab()
        {
            return selectedTab;
        }



        

    }

    
}
